package com.jin.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.jin.common.constant.AuthServerConstant;
import com.jin.common.exception.BizCodeEnume;
import com.jin.common.utils.HttpUtils;
import com.jin.common.utils.R;
import com.jin.common.vo.MemberRespVo;
import com.jin.gulimall.auth.feign.MemberFeignService;
import com.jin.gulimall.auth.feign.SmsFeignService;
import com.jin.gulimall.auth.service.AuthService;
import com.jin.gulimall.auth.vo.UserLoginVo;
import com.jin.gulimall.auth.vo.UserRegistVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Autowired
    AuthService authService;

    @Autowired
    SmsFeignService smsFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(attribute==null){
            //没有登录
            return "login";
        }else{
            return "redirect:http://gulimall.com";
        }
    }

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone){
        //先看缓存里是否存在验证码
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        //判断发送验证码是否在60秒之后了
        if(!StringUtils.isEmpty(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            //如果时间小于60秒，那么报错，不让再次发送
            if(System.currentTimeMillis()-l<60*1000){
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        String code = UUID.randomUUID().toString().substring(0, 4)+"_"+System.currentTimeMillis();
        //验证码的再次校验,redis
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,code,10, TimeUnit.MINUTES);
        String codeMessage = code.split("_")[0];
        smsFeignService.sendCode(phone, codeMessage);
        return R.ok();
    }


    //需要获取提交的表单数据，所以是post请求
    @PostMapping("/register")
    public String register(@Valid UserRegistVo vo, BindingResult result,
                           RedirectAttributes redirectAttributes,HttpSession session) throws IOException {
        if(result.hasErrors()){
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
//          不用model是因为若采用重定向的话，无法携带数据，所以采用redirectAttributes,利用的是session原理
//          model.addAttribute("errors", errors);
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //校验验证码
        String code = vo.getCode();
        String codeRedis = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if(!StringUtils.isEmpty(codeRedis)){
            if(code.equals(codeRedis.split("_")[0])){
                //验证码通过，要删除验证码，令牌机制
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //进行注册流程
                R r = memberFeignService.regist(vo);
                if(r.getCode()==0){
                    //注册成功回到首页，回到登录
                    return "redirect:http://auth.gulimall.com/login.html";
                }else{
                    Map<String, String> errors = new HashMap<>();
                    //传入msg设置key类型
                    errors.put("msg", r.getData("msg",new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            }else{
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }else{
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

    }




    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        //远程登录
        R r = memberFeignService.login(vo);
        if(r.getCode()==0){
            //登录成功
            MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);
            return "redirect:http://gulimall.com";
        }else{
            Map<String, String> errors = new HashMap<>();
            //fastjson
            errors.put("msg", r.getData("msg", new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
